package com.yuncheng.spcyApi.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.config.SpcyMinioUtils;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxWjjl;
import com.yuncheng.spcyApi.entity.SpcyZltxwjBasic;
import com.yuncheng.spcyApi.entity.SpcyZltxwjFlow;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcySqsxWjjlService;
import com.yuncheng.spcyApi.service.ISpcyZltxwjBasicService;
import com.yuncheng.spcyApi.service.ISpcyZltxwjFlowService;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.webOffice.WebOfficeFile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.Util;


import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Component(value = "HnCaUtils")
public class HnCaUtils {
    private static final Logger log = LoggerFactory.getLogger(HnCaUtils.class);

    @Resource
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private ISpcyZltxwjFlowService spcyZltxwjFlowService;

    @Resource
    @Lazy
    private ISpcyZltxwjBasicService spcyZltxwjBasicService;

    @Resource
    private BusinessConstant bussinessConstant;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private SpcyMinioUtils spcyMinioUtils;

    @Resource
    private WebOfficeFile webOfficeFIle;

    // 关键字（盖章规则）
//    private final static String GJZ_KEY = "HNCA_16722801353059"; // 旧的关键字
    private final static String GJZ_KEY = "HNCA_17050543481429"; // 新的关键字
    private final static String ZLTXWJ_ZBQZ_SK = "HNCA_17124780376228"; // 质量体系文件-坐标签章 受控
    private final static String ZLTXWJ_ZBQZ_SX = "HNCA_17124822939237"; // 质量体系文件-坐标签章 失效
//    private final static String QFZ_KEY = "HNCA_17083382157940"; // 新的骑缝章

    /** 对pdf文件盖章 关键字和骑缝章*/
    public HttpResult<?> fileCaToPDFByGJZ2(String id){
        SpcySqsxWjjl attachement = spcySqsxWjjlService.getById(id);
        if (attachement != null){
            String realStorageAddress = attachement.getFcflj();
            String docBase64 = "";
            String ruleList = GJZ_KEY;
//            String ruleList = "HNCA_16722801353059"; // 可用 HNCA_16722801353059 关键字 HNCA_16724754156165 骑缝章
//            String ruleList = "HNCA_16722801353059"; // 可用 HNCA_16722801353059 关键字
//            String ruleList = "HNCA_16724754156165"; // HNCA_16724754156165 骑缝章1  HNCA_16766256244972 骑缝章2

            String FilePath = localFileUploadUtils.getSqsxWjjlAbsUrl(realStorageAddress);
            //1.验证是否有pdf
            File file=new File(FilePath);
            if (!file.exists()) {
                log.error("未找到pdf");
                return HttpResult.ok("未找到pdf文件");
            }
            //2.转码签章
            docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//            log.info("开始构造云签章请求");
            String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//            log.info(res);

            //3.解析签章结果
            try {
                JSONObject jsonRes = JSONObject.parseObject(res);

                if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                    String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                    // 保存文件
                    HncaTool.decoderBase64File(fileData, FilePath);
                    res =  HncaTool.VerifySign(docBase64,FilePath);

                    attachement.setFgzzt(SpcyConstant.WJJL_ZT_GZ); // 盖章
                    attachement.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC);
                    spcySqsxWjjlService.updateById(attachement);

                    // minio上传
                    if (localFileUploadUtils.isEnableMinioWjjlFile()){
                        String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(realStorageAddress);
                        spcyMinioUtils.putFile(objectName,new File(FilePath),".pdf");
                    }

                } else {
                    log.error("出现错误");
                    log.error(jsonRes.getString("ErrorCode"));
                    log.error(jsonRes.getString("ErrorMsg"));
                }
            } catch (Exception ex) {
                log.error("错误数据：{}",ex.getMessage());
            }
            return HttpResult.ok("盖章成功");
        }
        return HttpResult.ok("文件不存在");
    }

    /**
     * 对本地文件盖章
     * @param outFilePdf 绝对路径
     * @param ruleList 盖章规则
     */
    public static void localAbsFileCa(String outFilePdf, String ruleList){
        String docBase64 = "";
        //1.验证是否有pdf
        File file=new File(outFilePdf);
        if (!file.exists()) {
            log.error("未找到pdf");
            return;
        }

        //2.转码签章
        docBase64 = HncaTool.FileEncodeBase64(outFilePdf); // 960KB
//        log.info("开始构造云签章请求");
        String res = HncaTool.ServerSign(docBase64, ruleList); // 构造云签章请求并等待服务器返回

        //3.解析签章结果
        try {
            JSONObject jsonRes = JSONObject.parseObject(res);

            if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                // 保存文件
                HncaTool.decoderBase64File(fileData, outFilePdf);
                HncaTool.VerifySign(docBase64, outFilePdf);

            } else {
                log.error("本地文件盖章出现错误");
                log.error(jsonRes.getString("ErrorCode"));
                log.error(jsonRes.getString("ErrorMsg"));
            }
        } catch (IOException ex) {
            log.error("本地文件盖章错误数据：{}",ex.getMessage());
        }

    }

    /** 申请事项-对pdf文件盖章 关键字盖章 */
    public HttpResult fileCaByGJZ(String id){
        return fileCaByGJZ(id, null);
    }

    /** 申请事项-对pdf文件盖章 关键字盖章 */
    public HttpResult<?> fileCaByGJZ(String id, SpcySqsxWjjl attachement){
        if (attachement == null) {
            attachement = spcySqsxWjjlService.getById(id);

            if (attachement == null){
                return HttpResult.error("当前文件不存在，请刷新重试");
            }
        }

        if (StringUtils.isBlank(attachement.getFwjlx()) || !attachement.getFwjlx().equals(".pdf")){
            return HttpResult.error("请先生成pdf文件。");
        }

        if (attachement != null){
            String realStorageAddress = attachement.getFcflj();
            String docBase64 = "";
            String ruleList = GJZ_KEY;
//            String ruleList = "HNCA_16722801353059"; // 可用 HNCA_16722801353059 关键字 HNCA_16724754156165 骑缝章
//            String ruleList = "HNCA_16722801353059"; // 可用 HNCA_16722801353059 关键字
//            String ruleList = "HNCA_16724754156165"; // HNCA_16724754156165 骑缝章

            String FilePath = "";
            if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                InputStream minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(realStorageAddress));
                if (minioInput == null){
                    return HttpResult.error("未找到文件");
                }
                File file = localFileUploadUtils.asFile(minioInput, attachement.getFwjlx());
                FilePath = file.getAbsolutePath();

            }else {
                //1.验证是否有pdf
                File file = new File(localFileUploadUtils.getSqsxWjjlAbsUrl(realStorageAddress));
                if (!file.exists()) {
                    log.error("未找到pdf");
                    return HttpResult.error("未找到pdf文件");
                }

                FilePath = file.getAbsolutePath();
            }

            //2.转码签章
//            docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//            log.info("开始构造云签章请求");
//            String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//            log.info(res);

            //3.解析签章结果
            try {
                docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
                String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
                JSONObject jsonRes = JSONObject.parseObject(res);

                if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                    String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                    // 保存文件
                    HncaTool.decoderBase64File(fileData, FilePath);
                    res =  HncaTool.VerifySign(docBase64,FilePath);

                    String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());
                    String wjccmc = GetUuIdUtils.NotReplaceUuId()+".pdf";
                    String newCflj = ml +"/"+ wjccmc;

                    boolean flag = true;
                    // minio上传
                    if (localFileUploadUtils.isEnableMinioWjjlFile()){
                        String oldMinioCflj = localFileUploadUtils.getSqsxWjjlRelativeUrl(realStorageAddress);
                        String newMinioCflj = localFileUploadUtils.getSqsxWjjlRelativeUrl(newCflj);
                        flag = spcyMinioUtils.putFlagFile(newMinioCflj, new File(FilePath),".pdf");
                        if (flag) {
                            spcyMinioUtils.remove(oldMinioCflj);
                        }
                    }

                    if (flag){
                        attachement = spcySqsxWjjlService.genWjjlByPdfGz(attachement, newCflj, wjccmc);

                        spcySqsxWjjlService.updateById(attachement);
                    }else {
                        return HttpResult.error("盖章文件上传失败！");
                    }

                } else {
                    log.error("申请事项盖章出现错误");
                    log.error(jsonRes.getString("ErrorCode"));
                    log.error(jsonRes.getString("ErrorMsg"));
                    return HttpResult.error(jsonRes.getString("ErrorMsg"));
                }
            } catch (Exception ex) {
                log.error("错误数据：{}",ex.getMessage());
            }
            return HttpResult.ok("申请事项盖章盖章成功");
        }
        return HttpResult.ok("盖章成功");
    }

    /** 质量体系文件(流程)-对pdf文件盖章 位置盖章 */
    public Result fileCaInZltxwjFlow(String id, SpcyZltxwjFlow attachement){
        if (attachement == null) {
            attachement = spcyZltxwjFlowService.getById(id);

            if (attachement == null){
                return Result.error("当前文件不存在，请刷新重试");
            }
        }

        boolean isPdf = false;
        if (StringUtils.isBlank(attachement.getFwjlx())){
            return Result.error("当前文件格式为空！");
        }else {
            if (attachement.getFwjlx().equals(".pdf")){
                isPdf = true;
            }else {
                if (!(attachement.getFwjlx().equals(".doc") || attachement.getFwjlx().equals(".docx"))) {
                    return Result.error("当前文件格式不符合！" + attachement.getFwjlx());
                }
            }
        }
        /*if (StringUtils.isBlank(attachement.getFwjlx())
                || !(attachement.getFwjlx().equals(".doc") || attachement.getFwjlx().equals(".docx"))){
            return Result.error("当前文件格式不符合！"+attachement.getFwjlx());
        }*/

        String nowWjlj = attachement.getFwjlj();
        String oldWjlj = attachement.getFjdwjlj();


        String wordUrl = ""; // 文档路径
        String parMl = ""; // pdf文件父路径
        if (bussinessConstant.isEnableZltxwnjMinio) {
            parMl = localFileUploadUtils.getTempFileRootUrl();
            InputStream minioInput = spcyMinioUtils.getObject(nowWjlj);
            if (minioInput == null){
                return Result.error("文件流程不存在！");
            }
            File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(nowWjlj));
            wordUrl = file.getAbsolutePath();
        }else {
            wordUrl = bussinessConstant.UPLOAD_FILE_ROOT + nowWjlj;

            parMl = bussinessConstant.UPLOAD_FILE_ROOT;
        }

        /**
         * 生产pdf文件版
         */
        String ml = "/" + SpcyConstant.Flow_Zltxwj_File_Base_Url + "/" + DateConversionUtils.DateToYear(new Date());
        File dir = new File(parMl + ml);
        if (!dir.exists()){
            dir.mkdirs();
        }
        String pdfUrl = ml + "/"+ GetUuIdUtils.ReplaceUuId()+".pdf";

        if (isPdf){
            boolean copyFlag = FileCopyUtils.copyFile(wordUrl, parMl+pdfUrl); // 复制文件
            if (!copyFlag){
                return Result.error("pdf文件流复制失败！");
            }
        }else {
            WordPdfUtils.wordToPdf(wordUrl, parMl + pdfUrl);
        }

        String docBase64 = "";

        String ruleList = ZLTXWJ_ZBQZ_SK;
        if (StringUtils.isNotBlank(attachement.getFxglx()) && attachement.getFxglx().equals(SpcyConstant.Zltxwj_Xdlx_SX)){
            ruleList = ZLTXWJ_ZBQZ_SX;
        }

        String FilePath = parMl + pdfUrl;
        //1.验证是否有pdf
        File file = new File(FilePath);
        if (!file.exists()) {
            log.error("未找到pdf");
            return Result.error("未找到pdf文件");
        }

        //2.转码签章
        docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//        log.info("开始构造云签章请求");
        String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//        log.info(res);

        //3.解析签章结果
        try {
            JSONObject jsonRes = JSONObject.parseObject(res);

            if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                // 保存文件
                HncaTool.decoderBase64File(fileData, FilePath);
                HncaTool.VerifySign(docBase64, FilePath);

                boolean flag = true;
                // minio上传
                if (bussinessConstant.isEnableZltxwnjMinio){
                    flag = spcyMinioUtils.putFlagFile(pdfUrl, new File(FilePath),".pdf");
                }

                if (flag){
                    if (StringUtils.isNotBlank(oldWjlj)){
                        localFileUploadUtils.deleteLocalFileUrlByZltxwj(oldWjlj);
                    }

                    spcyZltxwjFlowService.updateZltxwjFileInPdf(attachement.getId(), nowWjlj, pdfUrl);
                }else {
                    return Result.error("盖章文件上传失败！");
                }

            } else {
                log.error("流程体系文件出现错误");
                log.error(jsonRes.getString("ErrorCode"));
                log.error(jsonRes.getString("ErrorMsg"));
                return Result.error(jsonRes.getString("ErrorMsg"));
            }
        }catch (Exception ex) {
            log.error("流程体系文件错误数据：{}",ex.getMessage());
        }

        return Result.ok("盖章成功");
    }

    /** 质量体系文件(库)-对pdf文件盖章 位置盖章 */
    public Result fileCaInZltxwjBasic(String id, SpcyZltxwjBasic attachement, boolean isSx){
        if (attachement == null) {
            attachement = spcyZltxwjBasicService.getById(id);

            if (attachement == null){
                return Result.error("当前文件不存在，请刷新重试");
            }
        }

        if (StringUtils.isBlank(attachement.getFpdfurl())){
            return Result.error("请先生成pdf文件。");
        }

        if (attachement != null){
            String realStorageAddress = attachement.getFpdfurl();
            String docBase64 = "";
            String ruleList = "";
            if (isSx) {
                ruleList = ZLTXWJ_ZBQZ_SX;
            }else {
                ruleList = ZLTXWJ_ZBQZ_SK;
            }

            String FilePath = "";
            if (bussinessConstant.isEnableZltxwnjMinio) {
                InputStream minioInput = spcyMinioUtils.getObject(realStorageAddress);
                if (minioInput == null){
                    return Result.error("未找到文件流！");
                }

                File file = localFileUploadUtils.asFile(minioInput, ".pdf");
                FilePath = file.getAbsolutePath();

            }else {

                FilePath = bussinessConstant.UPLOAD_FILE_ROOT + realStorageAddress;
                //1.验证是否有pdf
                File file = new File(FilePath);
                if (!file.exists()) {
                    log.error("未找到pdf");
                    return Result.error("未找到pdf文件");
                }
            }

            //2.转码签章
            docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//            log.info("开始构造云签章请求");
            String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//            log.info(res);

            //3.解析签章结果
            try {
                JSONObject jsonRes = JSONObject.parseObject(res);

                if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                    String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                    // 保存文件
                    HncaTool.decoderBase64File(fileData, FilePath);
                    HncaTool.VerifySign(docBase64, FilePath);

                    String ml = "/"+SpcyConstant.Zltxwj_File_Base_Url+"/pdf/" + DateConversionUtils.DateToYear(new Date());
                    String wjccmc = GetUuIdUtils.ReplaceUuId()+".pdf";
                    String newCflj = ml +"/"+ wjccmc;

                    boolean flag = true;
                    // minio上传
                    if (bussinessConstant.isEnableZltxwnjMinio){
                        flag = spcyMinioUtils.putFlagFile(newCflj, new File(FilePath),".pdf");
                        if (flag) {
                            spcyMinioUtils.remove(realStorageAddress);
                        }
                    }else {
//                        localFileUploadUtils.deleteLocalFileUrlByZdy(realStorageAddress, false);
                        newCflj = realStorageAddress;
                    }

                    if (flag){

                        LambdaUpdateWrapper<SpcyZltxwjBasic> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(SpcyZltxwjBasic::getId, id);

                        SpcyZltxwjBasic updateBean = new SpcyZltxwjBasic();
                        updateBean.setFpdfurl(newCflj);
                        spcyZltxwjBasicService.update(updateBean, updateWrapper);

                        attachement.setFpdfurl(newCflj);
                    }else {
                        return Result.error("盖章文件上传失败！");
                    }

                } else {
                    log.error("体系文件盖章出现错误");
                    log.error(jsonRes.getString("ErrorCode"));
                    log.error(jsonRes.getString("ErrorMsg"));
                    return Result.error(jsonRes.getString("ErrorMsg"));
                }
            } catch (Exception ex) {
                log.error("体系文件盖章错误数据：{}",ex.getMessage());
            }

            return Result.ok(attachement);
        }

        return Result.ok(attachement);
    }

    /** 盖章-质量体系文件-
     * @param isSx 是否失效章
     * @param FilePath 本地绝对路径
     * */
    public Result fileCaInZltxwjBasicInLocal(String FilePath, boolean isSx){

        if (StringUtils.isBlank(FilePath)){
            return Result.error("请先生成pdf文件。");
        }

        String docBase64 = "";
        String ruleList = "";
        if (isSx) {
            ruleList = ZLTXWJ_ZBQZ_SX;
        }else {
            ruleList = ZLTXWJ_ZBQZ_SK;
        }

        //1.验证是否有pdf
        File file = new File(FilePath);
        if (!file.exists()) {
            log.error("未找到pdf");
            return Result.error("未找到pdf文件");
        }

        //2.转码签章
        docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//        log.info("开始构造云签章请求");
        String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//        log.info(res);

        //3.解析签章结果
        try {
            JSONObject jsonRes = JSONObject.parseObject(res);

            if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                // 保存文件
                HncaTool.decoderBase64File(fileData, FilePath);
                HncaTool.VerifySign(docBase64, FilePath);
                log.info("体系文件盖章成功");
                return Result.ok();

            } else {
                log.error("体系文件盖章出现错误");
                log.error(jsonRes.getString("ErrorCode"));
                log.error(jsonRes.getString("ErrorMsg"));
                return Result.error(jsonRes.getString("ErrorMsg"));
            }
        } catch (Exception ex) {
            log.error("体系文件盖章错误数据：{}",ex.getMessage());
            return Result.error(ex.getMessage());
        }
    }

    /** 盖章-法规标准库-
     * @param isSx 是否失效章
     * @param FilePath 本地绝对路径
     * */
    public Result fileCaInFgbzkBasicInLocal(String FilePath, boolean isSx){

        if (StringUtils.isBlank(FilePath)){
            return Result.error("请先生成pdf文件。");
        }

        String docBase64 = "";
        String ruleList = "";
        if (isSx) {
            ruleList = ZLTXWJ_ZBQZ_SX;
        }else {
            ruleList = ZLTXWJ_ZBQZ_SK;
        }

        //1.验证是否有pdf
        File file = new File(FilePath);
        if (!file.exists()) {
            log.error("未找到pdf");
            return Result.error("未找到pdf文件");
        }

        //2.转码签章
        docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
        String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回

        //3.解析签章结果
        try {
            JSONObject jsonRes = JSONObject.parseObject(res);

            if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                // 保存文件
                HncaTool.decoderBase64File(fileData, FilePath);
                HncaTool.VerifySign(docBase64, FilePath);
                log.info("法规标准库盖章成功");
                return Result.ok();

            } else {
                log.error("法规标准库盖章出现错误");
                log.error(jsonRes.getString("ErrorCode"));
                log.error(jsonRes.getString("ErrorMsg"));
                return Result.error(jsonRes.getString("ErrorMsg"));
            }
        } catch (Exception ex) {
            log.error("法规标准库盖章错误数据：{}",ex.getMessage());
            return Result.error(ex.getMessage());
        }
    }

    /** 申请事项文件转pdf */
    public void sqsxFileToMinio(SpcySqsxWjjl wjjl, String ml){
        // 判断是否为手动上传
        if (StringUtils.isNotBlank(wjjl.getFwjlx4()) && wjjl.getFwjlx4().equals(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC)) {
            // 手动上传不处理
            return;
        }else {
            // 不为手动上传

            String realurl = localFileUploadUtils.getTempFileRootUrl() + ml;

            if (wjjl.getFwjlx().equals(".doc") || wjjl.getFwjlx().equals(".docx")) {

                if (StringUtils.isNotBlank(wjjl.getFwjlx3()) && wjjl.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ)){
                    String pdfname = GetUuIdUtils.NotReplaceUuId() + ".pdf"; // 文件名称
                    String outFileUrl = realurl + "/" + pdfname;
                    String oldCflj = wjjl.getFcflj();

                    String outFile = "";
                    if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                        InputStream minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(oldCflj));
                        if (minioInput == null){
                            return;
                        }
                        File file = localFileUploadUtils.asFile(minioInput, wjjl.getFwjlx());
                        outFile = file.getAbsolutePath();

                    }else {
                        outFile = localFileUploadUtils.getSqsxWjjlAbsUrl(oldCflj);
                    }

                    WordPdfUtils.wordToPdf(outFile, outFileUrl);

                    String cflj = ml + "/" + pdfname;

                    boolean flag = false;
                    // minio上传
                    if (localFileUploadUtils.isEnableMinioWjjlFile()){
                        String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj);
                        flag = spcyMinioUtils.putFlagFile(objectName, new File(outFileUrl), ".pdf");

                    }else {
                        flag = true;
                    }

                    if (flag) {

                        if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                            localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
                        }

                        wjjl = spcySqsxWjjlService.genWjjlByScpdf(wjjl, cflj, oldCflj, pdfname);

                        spcySqsxWjjlService.updateById(wjjl);
                    }

                }
            }
        }
    }

    /**
     * 申请事项文件文档转pdf并盖章
     * @param wjjl
     * @param ml
     */
    public void sqsxFileToMinioGz(SpcySqsxWjjl wjjl, String ml){
        this.sqsxFileToMinioGz(wjjl, ml, true);
    }
    public void sqsxFileToMinioGz(SpcySqsxWjjl wjjl, String ml, boolean isGz){

        // 判断是否为手动上传
        if (StringUtils.isNotBlank(wjjl.getFwjlx4()) && wjjl.getFwjlx4().equals(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC)) {
            // 手动上传不处理
            return;
        }else {
            // 不为手动上传

            if (wjjl.getFwjlx().equals(".doc") || wjjl.getFwjlx().equals(".docx")) {

                if (StringUtils.isNotBlank(wjjl.getFwjlx3()) && wjjl.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ)){
                    boolean pdfFlag = false;
                    if (!pdfFlag){

                        boolean errorConvertPdf = false;

                        /*try {
                            webOfficeFIle.closeFile(wjjl.getId());
                        }catch (Exception e){

                        }

                        *//** 在线编辑转PDF *//*

                        try {
                            Result result1 = webOfficeFIle.getDocxToPdfFile(wjjl, wjjl.getFcflj());
                            if (result1.isSuccess()) {
                                *//** 盖章 *//*
                                if (isGz) {
                                    try {
                                        this.fileCaByGJZ(wjjl.getId());
                                    }catch (Exception e){
                                        log.error("文件id：{}；文件类型：{}", wjjl.getId(), wjjl.getFwjlx1());
                                        log.error("盖章失败：{}", e.getMessage());
                                    }
                                }
                            }else {
                                log.error("文件id：{}；文件类型：{}", wjjl.getId(), wjjl.getFwjlx1());
                                log.error("在线编辑转PDF错误：{}", result1.getMessage());

                                errorConvertPdf = true;
                            }
                        }catch (Exception e){
                            log.error("在线编辑转PDF失败！");
                            log.error("文件id：{}；文件类型：{}", wjjl.getId(), wjjl.getFwjlx1());
                            log.error("转PDF失败：{}", e.getMessage());

                            errorConvertPdf = true;
                        }*/

                        /** 异常-使用本地转换pdf */
                        if (errorConvertPdf) {
                            try {
                                wordConvertPdfWithSqsxWj(ml, wjjl, false);
                            }catch (Exception e){
                                log.error("使用本地转换pdf-异常：{}", e.getMessage());
                            }
                        }

                        return;
                    }

                    /*String cflj = ml + "/" + pdfname;
                    HttpResult result = this.localSqsxFileWdToPdfCaByGJZ(wjjl.getId(), wjjl, outFileUrl, cflj, pdfname);
                    if (!result.isSuccess() && (new File(outFileUrl).exists())){
                        boolean flag = false;
                        // minio上传
                        if (localFileUploadUtils.isEnableMinioWjjlFile()){
                            String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj);
                            flag = spcyMinioUtils.putFlagFile(objectName, new File(outFileUrl),".pdf");
                        }else {
                            flag = true;
                        }

                        if (flag) {
                            String oldCflj = wjjl.getFcflj();
                            wjjl = spcySqsxWjjlService.genWjjlByScpdfAndGz(wjjl, cflj, oldCflj, pdfname, false);

                            spcySqsxWjjlService.updateById(wjjl);
                        }
                    }*/
                }

            }else if (wjjl.getFwjlx().equals(".pdf")){
                if (StringUtils.isNotBlank(wjjl.getFwjlx3()) && wjjl.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_YSCPDF)){
                    /*if (isGz) {
                        try {
                            this.fileCaByGJZ(wjjl.getId(), wjjl);
                        }catch (Exception e){
                            log.error("文件id：{}；文件类型：{}", wjjl.getId(), wjjl.getFwjlx1());
                            log.error("盖章失败：{}", e.getMessage());
                        }
                    }*/
                }
            }
        }

    }

    /** 申请事项文件-文档转为pdf */
    public void wordConvertPdfWithSqsxWj(String ml, SpcySqsxWjjl wjjl, boolean isGz){
        log.error("申请事项文件-文档转为pdf: 文件名称: {}; 文件类型: {}", wjjl.getFwjxsmc(), wjjl.getFwjlx());
        String realurl = localFileUploadUtils.getTempFileRootUrl() + ml;
        String pdfname = GetUuIdUtils.NotReplaceUuId() + ".pdf"; // 文件名称
        String outFileUrl = realurl + "/" + pdfname;

        String outFile = "";
        if (localFileUploadUtils.isEnableMinioWjjlFile()) {
            InputStream minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(wjjl.getFcflj()));
            if (minioInput == null){
                return;
            }
            File file = localFileUploadUtils.asFile(minioInput, wjjl.getFwjlx());
            outFile = file.getAbsolutePath();

        }else {
            outFile = localFileUploadUtils.getSqsxWjjlAbsUrl(wjjl.getFcflj());
        }

        // 转pdf
        boolean pdfFlag = WordPdfUtils.wordToPdf(outFile, outFileUrl);
        if (!pdfFlag){
            return;
        }else {
            // 验证pdf文件是否损坏
            if (WordPdfUtils.isPdfCorrupted(outFileUrl)){
                return;
            }
        }

        String cflj = ml + "/" + pdfname;

        /** 盖章并上传 */
        boolean officeErrorFlag = true;
        /*if (isGz) {
            HttpResult result = this.localSqsxFileWdToPdfCaByGJZ(wjjl.getId(), wjjl, outFileUrl, cflj, pdfname);
            if (!result.isSuccess()) {
                officeErrorFlag = true;
            }
        }else {
            officeErrorFlag = true;
        }*/

        /** 保存未盖章的pdf文件 */
        if (officeErrorFlag) {
            boolean flag = false;
            // minio上传
            if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj);
                flag = spcyMinioUtils.putFlagFile(objectName, new File(outFileUrl), ".pdf");
            } else {
                flag = FileCopyUtils.copyFile(outFileUrl, localFileUploadUtils.getSqsxWjjlAbsUrl(cflj));
            }

            if (flag) {
                String oldCflj = wjjl.getFcflj();
                wjjl = spcySqsxWjjlService.genWjjlByScpdfAndGz(wjjl, cflj, oldCflj, pdfname, false);

                spcySqsxWjjlService.updateById(wjjl);
            }
        }

    }

    /**
     * 对申请事项本地文件盖章
     * @param id
     * @param FilePath 本地pdf绝对路径
     * @param cflj 新存放路径
     * @param wjccmc 存储文件名称
     * @return
     */
    public HttpResult localSqsxFileWdToPdfCaByGJZ(String id, SpcySqsxWjjl attachement, String FilePath, String cflj, String wjccmc){
        if (attachement == null) {
            attachement = spcySqsxWjjlService.getById(id);
        }

        if (attachement != null){

            String docBase64 = "";
            String ruleList = GJZ_KEY;

            //1.验证是否有pdf
            File file = new File(FilePath);
            if (!file.exists()) {
                log.error("未找到pdf");
                return HttpResult.error("未找到pdf文件");
            }

//            //2.转码签章
//            docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
//            log.info("开始构造云签章请求");
//            String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
//            log.info(res);

            //3.解析签章结果
            try {
                //2.转码签章
                docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
                String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回

                JSONObject jsonRes = JSONObject.parseObject(res);

                if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                    String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                    // 保存文件
                    HncaTool.decoderBase64File(fileData, FilePath);
                    res =  HncaTool.VerifySign(docBase64,FilePath);

                    boolean flag = false;
                    // minio上传
                    if (localFileUploadUtils.isEnableMinioWjjlFile()){
                        String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj);
                        flag = spcyMinioUtils.putFlagFile(objectName, new File(FilePath),".pdf");
                    }else {
                        flag = true;
                    }

                    if (flag){
                        String oldCflj = attachement.getFcflj();
                        attachement = spcySqsxWjjlService.genWjjlByScpdfAndGz(attachement, cflj, oldCflj, wjccmc, true);

                        spcySqsxWjjlService.updateById(attachement);
                    }

                } else {
                    log.error("申请事项本地文件盖章出现错误");
                    log.error(jsonRes.getString("ErrorCode"));
                    log.error(jsonRes.getString("ErrorMsg"));
                    return HttpResult.error(jsonRes.getString("ErrorMsg"));
                }
            } catch (Exception ex) {
                log.error("申请事项本地文件盖章错误数据：{}",ex.getMessage());
                return HttpResult.error(ex.getMessage());
            }
            return HttpResult.ok("盖章成功");
        }
        return HttpResult.ok("盖章成功");
    }

    /**
     * 质量体系文件-转pdf(流程文件)
     */
    public void zltxwjFlowFileConvertPdf(String zltxwjid){
        SpcyZltxwjFlow wjjl = spcyZltxwjFlowService.getById(zltxwjid);
        if (wjjl == null){
            return;
        }

        if (wjjl.getFwjlx().equals(".doc") || wjjl.getFwjlx().equals(".docx")) {

            String ml = SpcyConstant.Flow_Zltxwj_File_Base_Url + "/" + DateConversionUtils.DateToMonthTwo(new Date());
            String pdfname = GetUuIdUtils.NotReplaceUuId() + ".pdf"; // 文件名称
            String outPdfFileUrl = ""; // 输出路径
            String oldCflj = wjjl.getFwjlj();

            String outFile = "";
            if (bussinessConstant.isEnableZltxwnjMinio) {
                InputStream minioInput = spcyMinioUtils.getObject(oldCflj);
                if (minioInput == null){
                    return;
                }
                File file = localFileUploadUtils.asFile(minioInput, wjjl.getFwjlx());
                outFile = file.getAbsolutePath();

                outPdfFileUrl = localFileUploadUtils.getTempFileRootUrl();
            }else {
                outFile = bussinessConstant.UPLOAD_FILE_ROOT + oldCflj;

                outPdfFileUrl = bussinessConstant.UPLOAD_FILE_ROOT;

            }

            outPdfFileUrl += "/" + ml + "/" + pdfname;
            WordPdfUtils.wordToPdf(outFile, outPdfFileUrl);

            String newCflj = "/"+ ml + "/" + pdfname;

            boolean flag = true;
            // minio上传
            if (bussinessConstant.isEnableZltxwnjMinio){
                flag = spcyMinioUtils.putFlagFile(newCflj, new File(outPdfFileUrl), ".pdf");
            }

            if (flag) {
                spcyZltxwjFlowService.updateZltxwjFileInPdf(wjjl.getId(), oldCflj, newCflj);
                if (StringUtils.isNotBlank(wjjl.getFjdwjlj())){
                    localFileUploadUtils.deleteLocalFileUrlByZltxwj(wjjl.getFjdwjlj());
                }
            }else {
                throw new BusinessException("保存为pdf文件失败！");
            }

        }
    }
}
